#version 450 core

uniform sampler2D uAccumTexture;
uniform sampler2D uRevealageTexture;
uniform sampler2D uOpaqueTexture;
struct DirectionalLight {
    vec3 direction;
    vec4 color;
};
uniform DirectionalLight uLight;
uniform float uTime;
out vec4 color;

void main() {
    vec3 waterFaceNormal = vec3(0, 1, 0);
    float env = sin(uTime * 2 * 3.14159) * 0.05 + 0.05;
    float diff = max(dot(waterFaceNormal, normalize(-uLight.direction)), 0.0);
    float lightIntensity = env + diff * uLight.color.w;

    vec4 accum = texelFetch(uAccumTexture, ivec2(gl_FragCoord.xy), 0);
    float alpha = 1 - texelFetch(uRevealageTexture, ivec2(gl_FragCoord.xy), 0).r;
    vec3 transparentLayer = accum.rgb / clamp(accum.a, 1e-4, 5e4);
    vec4 opaqueLayer = texelFetch(uOpaqueTexture, ivec2(gl_FragCoord.xy), 0);

    vec3 composited = transparentLayer.rgb * lightIntensity * alpha + opaqueLayer.rgb * (opaqueLayer.a - alpha);
    color = vec4(composited, max(alpha, opaqueLayer.a));
}
